<template>
  <div class="production-plan">
      <!-- 修改按钮点击事件 -->
      <el-button type="primary" @click="saveAll">保存计划和明细</el-button>
      <el-button type="primary" @click="GetPackagingPlanlist">查看计划</el-button>
      <h3 class="title">新增计划</h3>
      <!-- 基本信息 -->
      <el-form :model="formData" :rules="rules" label-width="120px" ref="formRef">

          <el-row :gutter="20">
            <el-col :span="7">
                  <el-form-item label="计划类型" prop="planType">
                    <el-select
                      v-model="formData.planType"
                      clearable
                      placeholder="请选择"
                      style="width: 240px"
                    >
                      <el-option label="包装计划" value="1" />
                      <el-option label="过滤计划" value="2" />
                      <el-option label="生产计划" value="3" />
                      <el-option label="其他计划" value="4" />
                    </el-select>
                  </el-form-item>
              </el-col>
              <el-col :span="7">
                  <el-form-item label="计划日期" prop="scheduledDates">
                      <el-date-picker
                          v-model="formData.scheduledDates"
                          type="date"
                          readonly
                          required
                      ></el-date-picker>
                  </el-form-item>
              </el-col>
              <el-col :span="7">
                  <el-form-item label="规格" prop="packingSpecifications">
                      <el-input v-model="formData.packingSpecifications"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="7">
                  <el-form-item label="形式" prop="packagingForm">
                      <el-input v-model="formData.packagingForm"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="7">
                  <el-form-item label="产品系列" prop="productRange">
                      <el-input v-model="formData.productRange"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="7">
                  <el-form-item label="计划产量" prop="plannedProduction">
                      <el-input-number
                          v-model.number="formData.plannedProduction"
                          :min="0"
                      ></el-input-number>
                  </el-form-item>
              </el-col>
              <el-col :span="7">
                  <el-form-item label="产量单位" prop="productionUnits">
                      <el-input v-model="formData.productionUnits"></el-input>
                  </el-form-item>
              </el-col>
              <el-col :span="12">
                  <el-form-item label="备注 " prop="remark">
                      <el-input v-model="formData.remark" type="textarea" rows="3" required></el-input>
                  </el-form-item>
              </el-col>
          </el-row>
      </el-form>

      <!-- 计划明细 -->
      <div class="detail-section">
          <h7 class="sub-title">计划明细</h7>
          <el-button size="small" @click="addNewRow">新增行</el-button>
          <el-table :data="planDetailsList" border style="width: 100%">
              <!-- 车间名称下拉框 -->
              <el-table-column label="车间名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.workshopName"
                          :options="workshopOptions"
                          :value-key="workshopValueKey"
                          placeholder="请选择车间名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in workshopOptions"
                        :key="item.workshopId"
                        :label="item.workshopName"
                        :value="item.workshopName"
                      />
                    </el-select>
                  </template>
              </el-table-column>
              <!-- 工段名称下拉框 -->
              <el-table-column label="工段名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.workSectionName"
                          :options="workSectionOptions"
                          :value-key="workSectionValueKey"
                          placeholder="请选择工段名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in workSectionOptions"
                        :key="item.workSectionId"
                        :label="item.workSectionName"
                        :value="item.workSectionName"
                      />
                    </el-select>
                  </template>
              </el-table-column>
              <!-- 产线名称下拉框 -->
              <el-table-column label="产线名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.productionLineName"
                          :options="productionLineOptions"
                          :value-key="productionLineValueKey"
                          placeholder="请选择产线名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in productionLineOptions"
                        :key="item.productionLineId"
                        :label="item.productionLineName"
                        :value="item.productionLineName"
                      />
                    </el-select>
                  </template>
              </el-table-column>
              <!-- 设备名称下拉框 -->
              <el-table-column label="设备名称" width="180px">
                  <template #default="{ row }">
                      <el-select
                          v-model="row.deviceName"
                          :options="deviceOptions"
                          :value-key="deviceValueKey"
                          placeholder="请选择设备名称"
                          :disabled="row.productInfoFilled"
                          filterable
                      >
                      <el-option
                        v-for="item in deviceOptions"
                        :key="item.id"
                        :label="item.equipment_Name"
                        :value="item.equipment_Name"
                      />
                    </el-select>
                  </template>
              </el-table-column>
              <el-table-column label="开始日期" width="280px">
                  <template #default="{ row }">
                      <el-date-picker
                          v-model="row.friDate"
                          type="date"
                          @change="checkDateOrder(row)"
                      ></el-date-picker>
                  </template>
              </el-table-column>
              <el-table-column label="结束日期" width="280px">
                  <template #default="{ row }">
                      <el-date-picker
                          v-model="row.endDate"
                          type="date"
                          @change="checkDateOrder(row)"
                      ></el-date-picker>
                  </template>
              </el-table-column>
              <el-table-column label="负责人" width="180px">
                  <template #default="{ row }">
                <el-input
                  v-model="row.leader"
                  :disabled="row.productInfoFilled"
                  required
                >
                  <template #suffix>
                    <el-button size="mini" @click="openOurRepresentativesDialog">
                      <i class="el-icon-search"></i>
                    </el-button>
                  </template>
                </el-input>
                  </template>
              </el-table-column>
              <el-table-column label="人员数量" width="180px">
                  <template #default="{ row }">
                      <el-input-number
                          v-model.number="row.personnelNumber"
                          :min="0"
                      ></el-input-number>
                  </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="180px">
                  <template #default="{ row }">
                      <el-button size="small" type="danger" @click="deleteDetail(row)" :disabled="row.isSaved">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
      </div>

      
      <!-- 负责人选择对话框 -->
      <el-dialog
        v-model="ourRepresentativesDialogVisible"
        width="500px"
        title="负责人选择"
        append-to-body
      >
        <el-table
          :data="ourRepresentativesList"
          highlight-current-row
          border
          size="small"
          @current-change="handleOurRepresentativesChange"
        >
          <el-table-column type="index" label="序号" />
          <el-table-column property="userName" label="代表姓名" />
          <el-table-column property="depmentName" label="部门" />
          <el-table-column property="roleName" label="职位" />
        </el-table>
        <template #footer>
          <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
        </template>
      </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { read, write } from '@/axios/axiosHelper';
import { useCounterStore } from '@/stores/counter';
import router from '@/router';

const store = useCounterStore();
const formRef = ref(null);

// 主表单数据
const formData = reactive({
  preparation: true,
  picking: true,
  planType:'',
  packagingPlanId: null,
  scheduledDates: new Date(),
  packingSpecifications: "",
  packagingForm: "",
  productRange: "",
  plannedProduction: '',
  productionUnits: "",
  isload: 0,
  remark: ""
});

// 主表单验证规则
const rules = reactive({
  documentSubject: [
      { required: true, message: '单据主题不能为空', trigger: 'blur' }
  ],
  associatedItemNumber: [
      { required: true, message: '关联项目不能为空', trigger: 'blur' }
  ],
  documentMaker: [
      { required: true, message: '制单人员不能为空', trigger: 'blur' }
  ],
  scheduledDates: [
      { required: true, message: '制单日期不能为空', trigger: 'blur' }
  ],
  remark: [
      { required: true, message: '备注不能为空', trigger: 'blur' }
  ]
});

// 明细数据列表
const planDetailsList = ref([]);

// 关联项目数据
const associatedItems = ref([]);
// 产品名称数据
const productNames = ref([]);
// 物料清单数据
const billMaterialsList = ref([]);

// 车间、工段、产线、设备选项
const workshopOptions = ref([
      "workshopId",
      "workshopName"
]);
const workSectionOptions = ref([
      "workSectionId",
      "workSectionName"
]);
const productionLineOptions = ref([
      "productionLineId",
      "productionLineName"
]);
const deviceOptions = ref([
      "id",
      "equipment_Name",
      "model",
      "manufacturer",
      "purchase_Date",
      "status"
]);

const ourRepresentativesDialogVisible = ref(false);
  const ourRepresentativesList = ref([]);
  const currentOurRepresentative = ref(null);

  // 生命周期钩子
  onMounted(() => {
    fetchBaseData();
  });
  
  // 获取基础数据
  const fetchBaseData = () => {
    // 我方代表（员工代表）
    axios.get('http://8.154.44.176:8000/r-read/api/Depment/GetDepUserRole')
      .then(res => ourRepresentativesList.value = res.data.data || [])
      .catch(error => {
        ElMessage.error('加载我方代表失败');
        console.error(error);
      });
  };

  // 打开我方代表对话框
  const openOurRepresentativesDialog = () => {
    if (ourRepresentativesList.value.length === 0) {
      ElMessage.warning('我方代表数据加载中，请稍后重试');
      return;
    }
    ourRepresentativesDialogVisible.value = true;
  };
  
  // 处理我方代表行选中
  const handleOurRepresentativesChange = (val) => {
    currentOurRepresentative.value = val;
  };
  
  // 选择我方代表并填充数据
  const pickOurRepresentatives = () => {
  if (currentOurRepresentative.value) {
    const currentRowIndex = planDetailsList.value.findIndex(row => row.leader === '');
    if (currentRowIndex!== -1) {
      planDetailsList.value[currentRowIndex].leader = currentOurRepresentative.value.userName;
      planDetailsList.value[currentRowIndex].ourRepresentativesInfoFilled = true;
    }
    ourRepresentativesDialogVisible.value = false;
  } else {
    ElMessage.warning('请选择一个我方代表');
  }
};

// 对话框显示状态
const billMaterialsDialogVisible = ref(false);
const currentBillMaterialsRow = ref(null);
const currentBillMaterials = ref({});

// 下拉框 value-key
const workshopValueKey = ref('id'); // 根据实际数据调整
const workSectionValueKey = ref('id'); // 根据实际数据调整
const productionLineValueKey = ref('id'); // 根据实际数据调整
const deviceValueKey = ref('id'); // 根据实际数据调整

// 获取车间选项数据
const fetchWorkshopOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/Workshop/Handle')
    .then(res => {
          workshopOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取车间选项数据失败:', error);
          ElMessage.error('获取车间选项数据失败，请检查网络或联系管理员');
      });
};

// 获取工段选项数据
const fetchWorkSectionOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/WorkSection/Handle')
    .then(res => {
          workSectionOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取工段选项数据失败:', error);
          ElMessage.error('获取工段选项数据失败，请检查网络或联系管理员');
      });
};

// 获取产线选项数据
const fetchProductionLineOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/ProductionLine/Handle')
    .then(res => {
          productionLineOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取产线选项数据失败:', error);
          ElMessage.error('获取产线选项数据失败，请检查网络或联系管理员');
      });
};

// 获取设备选项数据
const fetchDeviceOptions = () => {
  axios.get('http://8.154.44.176:8000/p2-read/api/Equipment/GetEquipment')
    .then(res => {
          deviceOptions.value = res.data.data;
      })
    .catch(error => {
          console.error('获取设备选项数据失败:', error);
          ElMessage.error('获取设备选项数据失败，请检查网络或联系管理员');
      });
};

onMounted(() => {
  fetchWorkshopOptions();
  fetchWorkSectionOptions();
  fetchProductionLineOptions();
  fetchDeviceOptions();
});



// 保存主表单和明细
const saveAll = async () => {
  if (formRef.value) {
      const isValid = await formRef.value.validate();
      if (isValid) {
          try {
              // 保存主表单
              const response = await axios.post('http://8.154.44.176:8000/p2-write/api/PackagingPlan/AddPackagingPlan', formData);
              if (response.data.code === 200) {
                  formData.packagingPlanId = response.data.data.productionPlanningId;
                  console.log('表主键', formData.packagingPlanId);
                  ElMessage.success('主表单保存成功');

                  // 更新明细表的外键
                  const updatedDetails = planDetailsList.value.map(row => ({
                      ...row,
                      packagingPlanId: formData.packagingPlanId
                  }));

                  // 保存明细
                  const saveDetailPromises = updatedDetails.map(async (row) => {
                      const detailResponse = await axios.post(
                          'http://8.154.44.176:8000/p2-write/api/PackagingPlan/AddPackagingPlanDetails',
                          row
                      );
                      console.log("提交的数据"+row);
                      if (detailResponse.data.code === 200) {
                          row.isSaved = true;
                          return true;
                      } else {
                          ElMessage.error(`明细保存失败：${detailResponse.data.message}`);
                          return false;
                      }
                  });

                  const results = await Promise.all(saveDetailPromises);
                  if (results.every(result => result)) {
                      ElMessage.success('所有明细保存成功');
                  }
              } else {
                  ElMessage.error(`主表单保存失败：${response.data.message}`);
              }
          } catch (error) {
              console.error('保存过程中发生错误:', error.response?.data);
              ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
          }
      }
  }
};

// 新增行
const addNewRow = () => {
  planDetailsList.value.push({
      workshopName: "",
      workSectionName: "",
      productionLineName: "",
      deviceName: "",
      friDate: "",
      endDate: "",
      leader: "",
      personnelNumber: 0,
      packagingPlanId: ''
  });
};

// 删除单条明细
const deleteDetail = (row) => {
  ElMessageBox.confirm('确认删除该条明细？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
  }).then(() => {
      const index = planDetailsList.value.indexOf(row);
      if (index !== -1) {
          planDetailsList.value.splice(index, 1);
          ElMessage.success('明细删除成功');
      }
  }).catch(() => {
      ElMessage.info('取消删除');
  });
};

const headers = {};
const customRequest = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  const response = await axios.post(options.action, formData, {
      headers: headers
  });
  options.onSuccess(response.data);
  if (response.data) {
      ElMessage.success('文件上传成功');
  } else {
      ElMessage.error('文件上传失败');
  }
};

const handleError = (error) => {
  ElMessage.error('上传失败: ' + (error.response?.data?.error || error.message));
};

const uploadRef = ref(null);
const submitForm = () => {
  uploadRef.value.submit();
};

// 日期验证函数
const checkDateOrder = (row) => {
  const { friDate, endDate } = row;
  if (friDate && endDate && new Date(friDate) > new Date(endDate)) {
      ElMessage.error('结束日期不能小于开始日期');
      row.endDate = null;
  }
};

// 跳转包装计划列表
const GetPackagingPlanlist = () => {
  router.push('GetPackagingPlanlistView');
};
</script>

<style scoped>
.production-plan {
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.sub-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: 500;
}

.detail-section {
  width: 100%;
}

.attachment-section {
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}

.el-input[readonly],
.el-date-editor[readonly],
.el-input-number[disabled] {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>    